package com.filter;

import javax.servlet.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author wangshuai
 * @time 2015年12月22日
 */
public class CharacterEncodingfilter implements Filter{
	
	 //字符编码（初始化参数）
	 protected String encoding=null;
	 //FilterConfig对象
	 protected FilterConfig filterConfig=null;
	 public void init(FilterConfig filterConfig)throws ServletException
	 {
	  //对filterConfig赋值
	  this.filterConfig=filterConfig;
	  //对初始化参数赋值
	  this.encoding=filterConfig.getInitParameter("encoding");
	  
	  }
	 public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws UnsupportedEncodingException
	 {
	  //判断字符编码是否有效
	  if(encoding!=null)
	  {
	   //设置request字符编码
	   request.setCharacterEncoding(encoding);
	         //设置respongse字符编码
	   response.setContentType("text/html;charset="+encoding);
	  }
	  //传递给下一个过滤器
	  try {
	   chain.doFilter(request, response);
	  } catch (IOException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  } catch (ServletException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  }
	 
	 }
	 public void destroy()
	 {
	  //释放资源
	  this.encoding=null;
	  this.filterConfig=null;
	 }
}
